<style lang="scss" scoped>
@import "@/styles/mixins.scss";

.xjw-toast {
  .xjw-toast_main {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    padding: 16upx 32upx;
    box-sizing: border-box;
    word-break: break-all;
    font-size: 24upx;
    max-width: 300upx;
    text-align: center;
    @include thin-type-color;
    @include global-type-color("color");
    opacity: 0;
    transition: opacity 0.2s ease-in;
    border-radius: 8upx;
    z-index: 99;
    &--info {
      color: #fff;
    }
    &--thin-info {
      background: #585858;
    }
  }
  .xjw-toast--show {
    opacity: 1;
  }
}
</style>
<template>
  <view class="xjw-toast">
    <view
      class="xjw-toast_main"
      :class="[
        { 'xjw-toast--show': visible },
        'xjw-toast_main--thin-' + type,
        'xjw-toast_main--' + type,
      ]"
      :style="[toastStyle]"
      >{{ text }}</view
    >
  </view>
</template>

<script lang="ts">
import Vue from "vue";
import { Component } from "vue-property-decorator";
import { addUnit } from "../lib/function";
import { Ttype } from "../types/type";

type TToast = Ttype | "info";

interface toastProps {
  type: TToast;
  width: string;
  duration: number;
  text: string | number;
}

@Component
export default class Index extends Vue {
  timeId: number | null = null;
  visible: boolean = false;
  type: toastProps["type"] = "info";
  width: toastProps["width"] = "";
  duration: toastProps["duration"] = 2000;
  text: toastProps["text"] = "";

  get toastStyle() {
    return {
      width: this.width ? addUnit(this.width) : "auto",
    };
  }

  open(options: Partial<toastProps>) {
    const oList = Object.keys(options);
    if (oList.length > 0) {
      oList.forEach((key) => {
        this[key] = options[key];
      });
    }

    this.visible = true;
    this.timeId && clearTimeout(this.timeId);
    this.timeId = setTimeout(() => {
      this.close();
    }, this.duration);
  }

  close() {
    this.visible = false;
  }
}
</script>
